package cn.nexd.app.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.AutoCompleteTextView;
import android.widget.SearchView;
import android.widget.TextView;

import cn.nexd.app.activity.SearchActivity;

/**
 * Created by xun on 2016/5/11.
 */
public class MySearchView extends SearchView {
    private TextView textView;
    SearchActivity searchActivity;

    public void setSearchActivity(SearchActivity searchActivity) {
        this.searchActivity = searchActivity;
    }

    public MySearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setIconifiedByDefault(false);
        int id = context.getResources().getIdentifier("android:id/search_src_text", null, null);
        textView = (TextView) findViewById(id);
        LayoutParams layoutParams = (LayoutParams) textView.getLayoutParams();
        layoutParams.bottomMargin = -7;
        textView.setLayoutParams(layoutParams);
    }

    //按返回键不管searchView有没有焦点直接返回
    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {
        if (searchActivity != null &&
                event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            KeyEvent.DispatcherState state = getKeyDispatcherState();
            if (state != null) {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getRepeatCount() == 0) {
                    state.startTracking(event, this);
                    return true;
                } else if (event.getAction() == KeyEvent.ACTION_UP
                        && !event.isCanceled() && state.isTracking(event)) {
                    searchActivity.onBackPressed();
                    return true;
                }
            }
        }
        return super.dispatchKeyEventPreIme(event);
    }
}

